# -*- coding: utf-8 -*-
# 日志处理
# @Time    : 2024/12/9 下午5:35
# @Author  : 赵鑫源
# @FileName: my_logging.py
# @Software: PyCharm

import time
import os
import logging

current_path = os.path.dirname(__file__)
log_path = os.path.join(current_path, 'logs')
os.makedirs(log_path, exist_ok=True)


class LogUtils:
    formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

    def __init__(self, path=log_path):
        self.logfile_path = path
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)

        self._add_handler_if_not_exists(
            logging.FileHandler,
            filename=os.path.join(self.logfile_path, "IMAGE_SEARCH_%s" % time.strftime('%Y_%m_%d') + '.txt'),
            mode='a',
            encoding='utf-8'
        )

        self._add_handler_if_not_exists(logging.StreamHandler)

    def _add_handler_if_not_exists(self, handler_class, **kwargs):
        if not any(isinstance(handler, handler_class) for handler in self.logger.handlers):
            handler = handler_class(**kwargs)
            handler.setFormatter(self.formatter)
            handler.setLevel(logging.INFO)
            self.logger.addHandler(handler)

    def get_log(self):
        return self.logger
